<template>
  <CustomDialog ref="customDialog" width="600px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose">
    <template #header>
      {{ `${dialogProps.title}用户` }}
    </template>
    <template #content>
      <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :disabled="dialogProps.isView"
        :model="dialogProps.row" :hide-required-asterisk="dialogProps.isView">
        <el-form-item label="用户姓名" prop="username">
          <BInput v-model="dialogProps.row!.username" placeholder="请填写用户姓名" clearable :inputProps="{ maxlength: 50 }" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="dialogProps.row!.sex" placeholder="请选择性别" clearable>
            <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input v-model="dialogProps.row!.loginName" placeholder="请填写登录账号" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dialogProps.row!.password" placeholder="请填写密码" clearable type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="dialogProps.row!.phoneNumber" placeholder="请填写手机号码" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select v-model="dialogProps.row!.deptId" :data="treeSelectData" filterable check-strictly
            :props="treeSelectProps" :default-value="dialogProps.row.deptId" />
        </el-form-item>
        <el-form-item label="所属角色" prop="roles">
          <el-select v-model="dialogProps.row!.roles" placeholder="请选择角色" multiple clearable>
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogProps.row!.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in userStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import { genderType, userStatus } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";
import { getOrganicTree } from "@/api/modules/organize"
import { getAllRoleList } from '@/api/basic/role'
import { userDetails } from "@/api/modules/user";
import { useDataStore } from '@/stores/modules/data'

const dataStore = useDataStore()

const rules = reactive({
  username: [{ required: true, message: "请填写用户姓名" }],
  sex: [{ required: true, message: "请选择性别" }],
  loginName: [{ required: true, message: "请输入登录账号" }],
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {},
});

const customDialog = ref<InstanceType<typeof CustomDialog>>();

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  // dialogProps.value = params;
  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  dialogProps.value.isView = params.isView;
  if (JSON.stringify(params.row) !== '{}') {
    if (JSON.stringify(params.row) !== '{}') {
      const res: any = await userDetails(params.row.id);
      dialogProps.value.row = { ...res };
      // dialogProps.value.row.roles = res.role.map((role: any) => role.id);
      dialogProps.value.row.roles = res.role.map((role: any) => ({
        roleId: role.id,
        roleName: role.roleName
      }));
    }
  }

  customDialog.value?.acceptParams(true);
};

watch(() => dialogProps.value,
  (newValue) => {
    // console.log('66666', newValue);
  }, { immediate: true });

interface TreeNode {
  id: number;
  parentDepartmentId: number;
  departmentName: string;
  departmentType: number;
  children?: TreeNode[];
}

interface TreeSelectNode {
  value: number;
  label: string;
  children?: TreeSelectNode[];
}

//转换为树形结构
const convertToTreeSelectData = (data: TreeNode[]): TreeSelectNode[] => {
  return data.map(node => {
    const treeSelectNode: TreeSelectNode = {
      value: node.id,
      label: node.departmentName,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    };
    return treeSelectNode;
  });
}

onMounted(async () => {
  await dataStore.fetchRoleList();
  await dataStore.fetchDepartmentList()
});

// const roleList = computed(() => dataStore.roleList);
// const departmentList = computed(() => dataStore.departmentList);

// 获取部门树
const treeSelectData = ref<TreeSelectNode[]>([]);
const getOrganicTreeList = async () => {
  try {
    const res = await getOrganicTree();
    treeSelectData.value = convertToTreeSelectData(res);
  } catch (error) {
    console.log('获取部门列表失败', error);
  }
}
getOrganicTreeList()

//获取全部角色
const roleList = ref<any>([])
const getRoleList = async () => {
  try {
    const res = await getAllRoleList();
    roleList.value = res;
  } catch (error) {
    console.log('获取角色列表失败', error);

  }
};
getRoleList()
/**
 * 将包含角色对象和角色 ID 字符串的数组转换为角色 ID 数组
 * @param roles - 包含角色对象和角色 ID 字符串的数组
 * @returns 角色 ID 数组
 */
const convertRolesToRoleIds = (roles: Array<{ roleId: number; roleName: string } | string>): number[] => {
  return roles.map((role) => {
    if (typeof role === 'object') {
      return role.roleId;
    } else if (typeof role === 'string') {
      return parseInt(role, 10);
    }
  }).filter(Boolean) as number[]; // 过滤掉可能的 undefined 值
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    // 将角色名称转换为角色 ID
    dialogProps.value.row.roles = convertRolesToRoleIds(dialogProps.value.row.roles);
    dialogProps.value.row.roleIds = dialogProps.value.row.roles;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}用户成功！` });
      dialogProps.value.getTableList!();
      customDialog.value?.acceptParams(false);
      // ruleFormRef.value?.resetFields();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
  if (dialogProps.value.title !== '新增') {
    dialogProps.value.row = {}
  }
};

const treeSelectProps = {
  value: 'value',
  label: 'label',
  children: 'children'
};

defineExpose({
  acceptParams
});
</script>
